package com.huizu.common.utils.wx;

import com.huizu.common.utils.DateUtils;
import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Component
@Configuration
public class WechatTemplateMessage {

    public static void main(String[] args) {

    }

    public static void themMessage(Map<String,Object> map){
        String message = String.valueOf(map.get("message"));
        List<String> openIds = (List<String>)map.get("openIds");
        WxMpInMemoryConfigStorage wxStorage = new WxMpInMemoryConfigStorage();
        wxStorage.setAppId(WxUtils.puAppId); //appID
        wxStorage.setSecret(WxUtils.puAppSecret);//app密钥
        WxMpService wxMpService = new WxMpServiceImpl();
        wxMpService.setWxMpConfigStorage(wxStorage);
        //数据
        List<WxMpTemplateData> data = Arrays.asList(
                new WxMpTemplateData("thing6", message),
                new WxMpTemplateData("time2", DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,new Date()))
        );
        for (String openId : openIds) {
            //2,推送消息
            WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
                    .toUser(openId)//要推送的用户openid
                    .data(data) //数据
                    .templateId(WxUtils.themId)//模版id
                    .url("/pages/index/index") // 点击详情跳转地址
                    .build();
            //发起推送
            try {
                String msg = wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
                System.out.println("推送成功：" + msg);
            } catch (Exception e) {
                System.out.println("推送失败：" + e.getMessage());
                e.printStackTrace();
            }
        }
    }
}